package org.bjf.modules.user.web.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.bjf.config.CacheNameConfig.LocalCacheEnum.LocalCacheValue;
import org.bjf.exception.ServiceException;
import org.bjf.modules.core.web.core.LiveResp;
import org.bjf.modules.core.web.core.LoginRequired;
import org.bjf.modules.core.web.core.PageVO;
import org.bjf.modules.user.bean.User;
import org.bjf.modules.user.enums.RedisKey;
import org.bjf.modules.user.enums.UserMsgCode;
import org.bjf.modules.user.service.UserService;
import org.bjf.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

  @Autowired
  private UserService userService;
  @Autowired
  private RedisUtil redisUtil;

  @GetMapping("user/detail/{id}")
  @LoginRequired
  public User detail(@PathVariable long id) {
    if (id == 12) {
      //异常使用示例
      throw new ServiceException(UserMsgCode.USER_NOT_EXIST);
    }
    // redis使用示例
    redisUtil.setex(RedisKey.ACCESS_TOKEN.as("xxoo", "bbyy"), "myvalue", 10000);
    return userService.get(id);
  }

  @GetMapping("user/list")
  @Cacheable(value = LocalCacheValue.LOCAL, key = "'live:user:list'")
  public List<User> list(@RequestParam Map<String, String> params, HttpServletRequest request) {
    return userService.list(params);
  }

  @GetMapping("user/listPage")
  @CacheEvict(value = LocalCacheValue.LOCAL, key = "'live:user:list'")
  public PageVO<User> listPage(@RequestParam Map<String, String> params) {
    return userService.listPage(params);
  }

  @GetMapping("user/listAll")
  public List<User> listAll(@RequestParam Map<String, String> params) {
    return userService.listAll(params);
  }

  @GetMapping("user/listMap")
  public Object listMap(@RequestParam Map<String, String> params) {
    Map<Long, User> longUserMap = userService.mapByIds(Arrays.asList(10, 30), Long.class);
    return longUserMap;
  }

  @PostMapping("user/add")
  public LiveResp add(@Validated User user) {
    userService.add(user);
    return new LiveResp();
  }

  @PostMapping("user/update")
  public LiveResp update(@Validated User user) {
    userService.updateById(user);
    return new LiveResp();
  }

  @PostMapping("user/delete")
  public LiveResp delete(long id) {
    userService.delete(id);
    return new LiveResp();
  }


}
